package com.fin.zw.intelligentbot.service;

import com.fin.zw.intelligentbot.entity.*;
import com.fin.zw.intelligentbot.model.request.RoleInfoRequest;
import com.fin.zw.intelligentbot.repository.AccountRepository;
import com.fin.zw.intelligentbot.repository.ResourceRepository;
import com.fin.zw.intelligentbot.repository.RoleInfoRepository;
import com.querydsl.core.BooleanBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.*;

@Service("roleInfoService")
public class RoleInfoService {

    private static final Logger log = LoggerFactory.getLogger(RoleInfoService.class);

    @Autowired
    private RoleInfoRepository roleInfoRepository;

    @Autowired
    private AccountRepository accountRepository;

    @Autowired
    private ResourceRepository resourceRepository;

    /**
     * 查询所有的角色信息
     * @param pageable
     * @param request
     * @return
     */
    public Page<RoleInfo> queryRoleInfoAll(Pageable pageable,RoleInfoRequest request){
        BooleanBuilder builder = new BooleanBuilder();
        QRoleInfo qRoleInfo = QRoleInfo.roleInfo;
        if(request.getName() != null){
            builder.and(qRoleInfo.name.eq(request.getName()));
        }
        Page<RoleInfo> page = roleInfoRepository.findAll(builder,pageable);
        return page;
    }


    /**
     * 查询所有的角色（不分页）
     *
     * @return
     */
    public List<RoleInfo> getRoleInfoList() {
        List<RoleInfo> list = roleInfoRepository.findAll();
        return list;
    }

    /**
     * 角色的创建
     * @param request
     */
    public void createRoleInfo(RoleInfoRequest request){
        RoleInfo roleInfo = new RoleInfo();
        BeanUtils.copyProperties(request,roleInfo);
//        roleInfo.setWhether(Whether.YES);
        roleInfoRepository.save(roleInfo);
    }

    /**
     * 角色修改
     * @param request
     */
    public void updateRoleInfo(RoleInfoRequest request){
        Optional<RoleInfo> optional = roleInfoRepository.findById(request.getId());
        if(!optional.isPresent()){
            log.info("选择的角色不存在....");
            throw new RuntimeException("选择的角色不存在");
        }
        RoleInfo roleInfo = optional.get();
        roleInfo.setName(request.getName());
        roleInfo.setStatus(request.getStatus());
        roleInfo.setRemark(request.getRemark());
        roleInfo.setWhether(request.getWhether());

        if(request.getResources() != null && !request.getResources().isEmpty()){
            Set<Resource> set = new HashSet<>();
            Iterator<Resource> iterator = resourceRepository.findAll(QResource.resource.id.in(request.getResources())).iterator();
            while (iterator.hasNext()){
                Resource resource = iterator.next();
                set.add(resource);
            }
            roleInfo.setResources(set);
        }
        roleInfoRepository.save(roleInfo);
    }


    /**
     * 角色删除
     * @param id
     */
    public void deleteRoleInfoById(String id){
        Optional<RoleInfo> optional = roleInfoRepository.findById(id);
        if(!optional.isPresent()){
            log.info("选择的角色不存在....");
            throw new RuntimeException("选择的角色不存在");
        }
        RoleInfo roleInfo = optional.get();
        Iterator<Account> accountIterator = accountRepository.findAll(QAccount.account.roleInfoSet.contains(roleInfo)).iterator();
        if(accountIterator.hasNext()){
            log.info("该角色已经被用户绑定，请先解绑....");
            throw new RuntimeException("该角色已经被用户绑定，请先解绑");
        }
        roleInfoRepository.delete(roleInfo);
    }
}
